package com.canbot.u05.activity.presidemode;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.canbot.u05.R;
import com.canbot.u05.adapter.HostModeListViewAdapter;
import com.canbot.u05.bean.JsonResponse;
import com.canbot.u05.bean.guide.MapVoiceAndEyes;
import com.canbot.u05.bean.preside.PresideTask;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgSendUtils;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.view.HostModeDialog;
import com.canbot.u05.widget.LoadingDialogUtils;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author zmp
 * 主持模式首页任务列表（设置任务相关的界面---- 包括 添加任务，删除任务）
 */
public class HostModeListViewActivity extends BaseCompereActivity{

        private static final String TAG = "HostModeListViewActivit";

        public static final int PRESIDE_SERVLET_TYPE_ADD = 0;

        public static final int PRESIDE_SERVLET_TYPE_DELETE = 1;

        public static final int PRESIDE_SERVLET_TYPE_RENAME = 2;

        public static final int PRESIDE_SERVLET_TYPE_UPDATE = 3;

        public static final int PRESIDE_SERVLET_TYPE_QUERY_ALL = 4;

        public static final int PRESIDE_SERVLET_TYPE_TASK_RUN = 5;

        public static final int PRESIDE_SERVLET_TYPE_TASK_START = 6;

        public static final int PRESIDE_SERVLET_TYPE_NODE_START = 7;

        public static final int PRESIDE_SERVLET_TYPE_NODE_STOP = 8;

        protected static CopyOnWriteArrayList<PresideTask> mListData = new CopyOnWriteArrayList<>();

        private ListView listView;

        private HostModeListViewAdapter list_ada;

        public int currentPosition;

        private View ivOk;

        private View ivPb;

        private TextView tvLoad;

        private ToastTools toastTools;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.act_hostmode_list);
                toastTools = ToastTools.newInstance(this);
                MapVoiceAndEyes.playMapVoiceAndEyes(MapVoiceAndEyes.voiceEyesList.get(18));
                initView();

        }

        private void initView() {
                listView = (ListView) findViewById(R.id.listView);
                list_ada = new HostModeListViewAdapter(this, mListData);
                listView.setAdapter(list_ada);
                list_ada.setListner(new HostModeListViewAdapter.AdapterOnclickListner(){
                        @Override
                        public void onclick(int id) {
                                showTaskDialog(id);
                        }

                        @Override
                        public void showPopuwindow(int position) {
                                currentPosition = position;
                        }

                        @Override
                        public void doTask() {  // 执行  运行任务
                                Intent intent = new Intent(HostModeListViewActivity.this, AddTaskMainActivity.class);
                                intent.putExtra("taskInfo", JSON.toJSONString(list_ada.getItem(currentPosition)));
                                intent.putExtra("position", currentPosition);
                                startActivity(intent);
                        }
                });

                listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                currentPosition = position;
                                handTaskStart();
                        }
                });
                initData();
        }


        @Override
        protected void onResume() {
                super.onResume();
                list_ada.notifyDataSetChanged();
        }

        private void handTaskStart() {
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.loading));
                final String toJSONString = JSON.toJSONString(list_ada.getItem(currentPosition));
                HashMap<String, Object> hasMap = new HashMap<>();
                hasMap.put("type", PRESIDE_SERVLET_TYPE_TASK_START);
                hasMap.put("data", toJSONString);
                OkHttpUtils.upLoadFile("http://" + IpMsgConst.SOCKET_HOST2 + ":7755/" + "presenterMsg", hasMap, new OkHttpUtils.OkHttpCallBack(){
                        @Override
                        public void onSuccess(String result) {
                                Logger.e(TAG, "onSuccess:" + result);
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                Intent intent = new Intent(HostModeListViewActivity.this, PresideTaskRunActivity.class);
                                intent.putExtra("taskInfo", toJSONString);
                                startActivity(intent);
                        }

                        @Override
                        public void onFailure() {
                                Logger.e(TAG, "onFailure");
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                toastTools.showText("服务器异常");
                        }
                });
        }
        private Dialog dialogLoading;
        /**
         * 初始化数据
         */
        private void initData() {
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.loading));
                HashMap<String, Object> hasMap = new HashMap<>();
                hasMap.put("type", PRESIDE_SERVLET_TYPE_QUERY_ALL);
                OkHttpUtils.upLoadFile("http://" + IpMsgConst.SOCKET_HOST2 + ":7755/" + "presenterMsg", hasMap, new OkHttpUtils.OkHttpCallBack(){
                        @Override
                        public void onSuccess(String result) {
                                //                String replaceAll = result.replaceAll("\\\\", "");
                                Logger.e(TAG, "onSuccess:" + result);
                                JsonResponse jsonResponse = JSON.parseObject(result, JsonResponse.class);
                                if(jsonResponse.getRc() == 0) {
                                        List<PresideTask> presenterTasks = JSONArray.parseArray(jsonResponse.getMsg(), PresideTask.class);
                                        mListData.clear();
                                        if(presenterTasks != null) {
                                                mListData.addAll(presenterTasks);
                                        }
                                        runOnUiThread(new Runnable(){
                                                @Override
                                                public void run() {
                                                        list_ada.notifyDataSetChanged();
                                                }
                                        });
                                }
                                LoadingDialogUtils.closeDialog(dialogLoading);

                        }

                        @Override
                        public void onFailure() {
                                Logger.e(TAG, "onFailure");
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                toastTools.showText("服务器异常");
                        }
                });

        }

        //添加任务对话框
        public void showTaskDialog(int id) {
                final HostModeDialog dialog = new HostModeDialog(this, id);
                dialog.setListner(new HostModeDialog.ModeDialogOclickListner(){
                        @Override
                        public void onClick(int id) {
                                switch(id) {
                                        case R.id.btn_cancel:
                                                dialog.dismiss();
                                                break;
                                        case R.id.btn_normal://删除
                                                dialog.dismiss();
                                                deleteTask();
                                                break;
                                        case R.id.btn_rename_cancel:
                                                dialog.dismiss();
                                                break;
                                        case R.id.btn_rename_normal://换名
                                                String etName = dialog.getEtName();
                                                if(TextUtils.isEmpty(etName)) {
                                                        toastTools.showText("任务名不能为空哦！");
                                                        return;
                                                }
                                                for(PresideTask presenterTask : mListData) {
                                                        if(etName.equals(presenterTask.getTaskName())) {
                                                                toastTools.showText("任务名不能重复哦！") ;
                                                                return;
                                                        }
                                                }
                                                dialog.dismiss();
                                                renameTask(etName);
                                                break;

                                }
                        }
                });
                dialog.show();
                setDialogWindowAttr(dialog, this);
        }

        @Override
        protected void onRestart() {
                super.onRestart();
        }

        /**
         * 删除任务
         */
        private void deleteTask() {
                Logger.e(TAG, "onSuccess:" + currentPosition);
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.loading));
                PresideTask presideTask = mListData.get(currentPosition);
                HashMap<String, Object> hasMap = new HashMap<>();
                hasMap.put("type", PRESIDE_SERVLET_TYPE_DELETE);
                hasMap.put("data", presideTask.getTaskName());
                OkHttpUtils.upLoadFile(IpMsgConst.HTTP_URL_CHEST + "presenterMsg", hasMap, new OkHttpUtils.OkHttpCallBack(){

                        @Override
                        public void onSuccess(String result) {
                                Logger.e(TAG, "onSuccess:" + result);
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                mListData.remove(currentPosition);
                                runOnUiThread(new Runnable(){
                                        @Override
                                        public void run() {
                                                list_ada.notifyDataSetChanged();
                                        }
                                });
                        }

                        @Override
                        public void onFailure() {
                                Logger.e(TAG, "onFailure");
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                toastTools.showText("服务器异常!");
                        }
                });
        }

        /**
         * 重命名任务
         *
         * @param etName
         */
        private void renameTask(final String etName) {
                final PresideTask presenterTask = mListData.get(currentPosition);
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.loading));
                HashMap<String, Object> hasMap = new HashMap<>();
                hasMap.put("type", PRESIDE_SERVLET_TYPE_RENAME);
                hasMap.put("oldName", presenterTask.getTaskName());
                hasMap.put("newName", etName);
                OkHttpUtils.upLoadFile(IpMsgConst.HTTP_URL_CHEST + "presenterMsg", hasMap, new OkHttpUtils.OkHttpCallBack(){
                        @Override
                        public void onSuccess(String result) {
                                presenterTask.setTaskName(etName);
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                Logger.e(TAG, "onSuccess:" + result);
                                toastTools.showText("onSuccess");
                                runOnUiThread(new Runnable(){
                                        @Override
                                        public void run() {
                                                list_ada.notifyDataSetChanged();
                                        }
                                });
                        }

                        @Override
                        public void onFailure() {
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                Logger.e(TAG, "onFailure");
                                toastTools.showText("服务器异常!");
                        }
                });
        }

        //设置对话框显示
        public static void setDialogWindowAttr(Dialog dlg, Context ctx) {
                Window window = dlg.getWindow();
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.gravity = Gravity.CENTER;
                lp.width = (int) ctx.getResources().getDimension(R.dimen.x540);//宽高可设置具体大小
                lp.height = (int) ctx.getResources().getDimension(R.dimen.x278);
                dlg.getWindow().setAttributes(lp);
        }

        //返回键
        public void back(View view) {
                this.finish();
                overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
        }

        //添加键
        public void add(View view) {
                Intent intent = new Intent(this, AddTaskMainActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
        }

        @Override
        public void onBackPressed() {
                MsgSendUtils.sendStringMsg(MsgType.RECEIVER_3288_PRESIDE_EXIT, "主持人模式");
                super.onBackPressed();
        }

}